package reflect;

import org.junit.Test;

import javax.xml.transform.Source;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/*
* 调用运行时类的指定的结构:属性,方法,构造器
*
* */
public class MethodTest2 {
    @Test
    public void testField() throws NoSuchFieldException, IllegalAccessException, InstantiationException {
        Class<Person> personClass = Person.class;

        //创建运行时类的对象
        Person person = personClass.newInstance();

        //获取指定的属性:要求是public的属性
        //通常不采用此方法
        Field name = personClass.getField("age");

        //设置指定属性的值
        name.set(person,18);

        //获取指定属性的值
        Object o = name.get(person);
        System.out.println(o);
    }

    @Test
    public void test2() throws IllegalAccessException, InstantiationException, NoSuchFieldException {
        Class<Person> personClass = Person.class;

        Person person = personClass.newInstance();

        //获取类中的所有的属性
        Field name = personClass.getDeclaredField("name");

        //设置此属性可访问(可以设置,修改值)
        name.setAccessible(true);
        name.set(person,"小李");

        Object o = name.get(person);
        System.out.println(o);
    }

    @Test
    public void test3() throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException {
        Class<Person> personClass = Person.class;
        Person person = personClass.newInstance();

        //获取指定的某个方法
        Method setAge = personClass.getDeclaredMethod("setAge", int.class);

        //保证方法是可访问的
        setAge.setAccessible(true);

        //invoke调用方法:返回值就是调用的方法的返回值
        Object chn = setAge.invoke(person,123);
    }
}
